package com.nanxhs.structure.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 *
 * 层级遍历迭代器
 * @author 唐海斌
 * @version 1.0
 * @date 2021/5/25 10:00
 */
public class TopIterator {

    private List<Integer> dataList;

    private final Tree.TreeNode root;

    public TopIterator(Tree.TreeNode root) {
        this.root = root;
    }

    public List<Integer> iterator() {
        dataList = new ArrayList<>(10);
        Queue<Tree.TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Tree.TreeNode node = queue.poll();
            dataList.add(node.getElement());
            if (node.getChildrenLeft() != null) {
                queue.add(node.getChildrenLeft());
            }
            if (node.getChildrenRight() != null) {
                queue.add(node.getChildrenRight());
            }
        }
        return dataList;
    }
}
